﻿using System;

namespace D3StockChart.Tester
{
    public class PriceFeeder
    {
        public int TickWidth = 5; //1=nsmall, 5=big
        public decimal TickValue = 0.01m; //0.01 for stock, 0.10 for gold
        public int Direction = 0; //down -100 to 100 up
        private Random _rand = new Random();
        private const int SWINGTHRESHOLD = 100;

        private decimal _lastPrice;

        public PriceFeeder(decimal startPrice)
        {
            _lastPrice = startPrice;
        }

        public decimal NextPrice()
        {
            Direction = _rand.Next(-100, 100);
            decimal delta = _generatePriceChange(Direction);
            _lastPrice = _lastPrice + delta;
            return _lastPrice;
        }

        private decimal _generatePriceChange(int direction)
        {
            return _generatePriceChange(direction, TickWidth, TickValue, SWINGTHRESHOLD);
        }

        //direction is -100 to 100
        private decimal _generatePriceChange(int direction, int tickwidth, decimal tickvalue, int swingthreshold)
        {
            int r = _rand.Next(0, 201) - 100 + direction;
            int tick = _rand.Next(1, tickwidth + 1);
            decimal delta = tick * tickvalue;
            decimal swing = Math.Abs(r);
            if (swing > swingthreshold)
            {
                swing = (swing * 1.2m / 100m);
                //rounding to nearest tickvalue
                decimal leftover = swing % tickvalue;
                swing = 1m + swing - leftover;
                delta = Math.Floor(delta * swing * 100) / 100;
            }
            if (r < 0)
                delta = -1 * delta;
            return delta;
        }
    }
}
